<template>
    <div class="e-table">
        <!-- 头部buttons -->
        <div class="top">
            <div class="left">
                <div>
                    <el-button size="small" @click="downFile">下载</el-button>
                    <el-button
                        slot="reference"
                        size="small"
                        @click="deleteData"
                        v-if="auditState.canModify"
                        >删除</el-button
                    >
                    <el-button
                        size="small"
                        style="padding: 10px 30px"
                        class="btn-greenYellow"
                        @click="clientSelect"
                        v-if="auditState.canModify"
                        >选择公文</el-button
                    >
                    <!-- <el-button size="small" @click="save">测试保存</el-button> -->
                </div>
            </div>
        </div>
        <el-table
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="selectionChange"
            @cell-click="cellClick"
            :max-height="$store.state.tableHeight"
            ref="table"
            v-sortTable="{ tableData: tableData, _this: this, ref: 'table' }"
        >
            <el-table-column show-overflow-tooltip width="55" type="selection"> </el-table-column>
            <el-table-column show-overflow-tooltip type="index" label="序号" width="50">
            </el-table-column>
            <el-table-column
                show-overflow-tooltip
                prop="documentNo"
                label="文件编号"
                width="140"
                class-name="blue-column"
            >
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="name" label="公文文件名称" min-width="200">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="oaCreatTime" label="备案时间" width="160">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="createUser" label="备案人" width="100">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="gmtCreate" label="上传时间" width="160">
            </el-table-column>
        </el-table>
        <!-- <ComPagination
            :total="pagination.total"
            :pageSize.sync="pagination.pageSize"
            :currentPage.sync="pagination.currentPage"
            @currentChange="documentListByEntity"
            @sizeChange="documentListByEntity"
        /> -->
    </div>
</template>
<script>
// import ComPagination from '@/components/pagination/pagination.vue'
// import tenderRequest from '@/api/tender/tender.js'
// import applyRequest from '@/api/tender/apply.js'
import tenderRequest from '@/api/tender/tender.js'
import applyRequest from '@/api/tender/apply.js'
import engineeringOtherRequest from '@/api/tender/engineeringOther.js'
import materialProvisioningRequest from '@/api/tender/materialProvisioning.js'
import materialZhouCaiLeasingRequest from '@/api/tender/materialZhouCaiLeasing.js'
import materialServiceProcurementRequest from '@/api/tender/materialServiceProcurement.js'
import equipmentProcurementRequest from '@/api/tender/equipmentProcurement.js'
import equipmentLeasingRequest from '@/api/tender/equipmentLeasing.js'
// eslint-disable-next-line no-unused-vars
import { selectDataClient, openAppClient } from '@/utils/common'
import { mapState, mapMutations } from 'vuex'
// import commonRequest from '@/api/tender/common.js'

export default {
    props: {
        // 来自哪个招标模块，调用不同请求接口
        com: {
            type: String,
            default: ''
        },
        auditState: {
            type: Object,
            default: function () {
                return {}
            }
        }
    },
    data () {
        return {
            tableData: [],
            selection: [],
            cloneTableData: []
        }
    },
    computed: {
        tenderId () {
            return this.$route.query.tenderId || this.$route.query.billid
        },
        ...mapState({
            userInfo: state => state.userInfo
        }),
        SelectedIDs () {
            return this.tableData.map(item => item.documentNo).filter(item => item)
        }
    },
    components: {
        // ComPagination
    },
    created () {
        setTimeout(() => {
            console.log('auditState', this.auditState)
        }, 3000)
        this.documentListByEntity()
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        cellClick (row, column) {
            if (column.label === '文件编号') {
                window.open(row.filePath)
            }
        },
        deleteData () {
            const length = this.selection.length
            this.clientPop(
                'info',
                `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
                this.delFiles
            )
        },
        // 选择
        clientSelect () {
            console.log('SelectedIDs', this.SelectedIDs)
            // alert(this.SelectedIDs)
            selectDataClient({
                SelectServiceToken: '/tender/document/listByEntity', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: this.SelectedIDs, // 已选中id
                Title: '选择公文', // 标题
                OrgId: this.userInfo.orgInfo.orgId
            }).then(val => {
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                val.forEach(item => {
                    [
                        {
                            dispatNum: null,
                            docNum: '收文20229261031',
                            docStr: 'http://newoa.scrbg.com//PDFFile/In/42607/13308631451636639842607.pdf',
                            name: '关于调整四川公路桥梁建设集团有限公司大桥工程分公司职业健康安全生产委员会的通知',
                            oaCreateTime: '2022/9/26 10:04:11',
                            userName: '杨定军'
                        }
                    ]
                    const getNowDate = () => {
                        var date = new Date()
                        var sign2 = ':'
                        var year = date.getFullYear() // 年
                        var month = date.getMonth() + 1 // 月
                        var day = date.getDate() // 日
                        var hour = date.getHours() // 时
                        var minutes = date.getMinutes() // 分
                        var seconds = date.getSeconds() //秒
                        // var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天']
                        // var week = weekArr[date.getDay()]
                        // 给一位数的数据前面加 “0”
                        if (month >= 1 && month <= 9) {
                            month = '0' + month
                        }
                        if (day >= 0 && day <= 9) {
                            day = '0' + day
                        }
                        if (hour >= 0 && hour <= 9) {
                            hour = '0' + hour
                        }
                        if (minutes >= 0 && minutes <= 9) {
                            minutes = '0' + minutes
                        }
                        if (seconds >= 0 && seconds <= 9) {
                            seconds = '0' + seconds
                        }
                        return year + '-' + month + '-' + day + ' ' + hour + sign2 + minutes + sign2 + seconds
                    }
                    item.gmtCreate = getNowDate()
                    // item.oaCreateTime = item.oaCreateTime.replace(/\//g, '-')
                    item.documentNo = item.docNum
                    item.oaCreatTime = item.oaCreateTime.replace(/\//g, '-')
                    item.createUser = item.userName
                    item.filePath = item.docStr
                    // item.changeType = 1
                    item.billId = this.tenderId
                    if (this.cloneTableData.find(item2 => item2.documentNo === item.documentNo)) {
                        item.changeType = 0
                    } else {
                        item.changeType = 1
                    }
                })
                this.tableData = val
                this.save()
                // this.setSelectedInfo(this.tableData)
                // openAppClient('/showSelectedData', '选择结果', function () {})
            })
            // this.setSelectedInfo(this.tableData)
            // openAppClient('/showSelectedData', '选择结果', function () {})
        },
        ifEdit (newData, oldData) {
            newData = JSON.stringify(newData)
            // JSON.parase克隆的对象不存在会返回undfined
            oldData = JSON.stringify(oldData) || JSON.stringify([])
            if (newData !== oldData) {
                return true
            } else {
                return false
            }
        },
        // 保存
        async save () {
            // this.setSelectedInfo(this.tableData)
            // openAppClient('/showSelectedData', '选择结果', function () {})
            // alert(111)
            // alert(this.com)
            // this.setSelectedInfo(this.tableData)
            // openAppClient('/showSelectedData', 'this.tableData', function () {})
            if (this.com === 'bidding') {
                // alert(222)
                // this.setSelectedInfo(this.tableData)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                this.ifEdit(this.tableData, this.CloneTableData)
                    ? await applyRequest.documentCreate(this.tableData)
                    : null
            } else if (this.com === 'otherBidding') {
                // this.setSelectedInfo(this.tableData)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                this.ifEdit(this.tableData, this.CloneTableData)
                    ? await engineeringOtherRequest.documenSave(this.tableData)
                    : null
            } else if (this.com === 'materialBidding') {
                this.ifEdit(this.tableData, this.CloneTableData)
                    ? await materialProvisioningRequest.documenSave(this.tableData)
                    : null
            } else if (this.com === 'hireBidding') {
                this.ifEdit(this.tableData, this.CloneTableData)
                    ? await materialZhouCaiLeasingRequest.documenSave(this.tableData)
                    : null
            } else if (this.com === 'serviceBidding') {
                this.ifEdit(this.tableData, this.CloneTableData)
                    ? await materialServiceProcurementRequest.documenSave(this.tableData)
                    : null
            } else if (this.com === 'equipmentBidding') {
                this.ifEdit(this.tableData, this.CloneTableData)
                    ? await equipmentProcurementRequest.documenSave(this.tableData)
                    : null
            } else if (this.com === 'equipHireBidding') {
                this.ifEdit(this.tableData, this.CloneTableData)
                    ? await equipmentLeasingRequest.documenSave(this.tableData)
                    : null
            }
            this.documentListByEntity()
        },
        // 删除公文
        delFiles () {
            // const ids = this.tableData.map(item => item.recordId).filter(item => item)
            // const ids = this.selection.map(value => value.recordId).join(',')
            const ids = this.selection.map(value => value.recordId)
            if (ids.length === 0) return
            const callBack = () => {
                this.documentListByEntity()
            }
            if (this.com === 'bidding') {
                applyRequest.documentDelete(ids).then(() => {
                    this.clientPop('suc', '删除成功', callBack)
                })
            } else if (this.com === 'otherBidding') {
                engineeringOtherRequest.documenDelete(ids).then(() => {
                    this.clientPop('suc', '删除成功', callBack)
                })
            } else if (this.com === 'materialBidding') {
                materialProvisioningRequest.documenDelete(ids).then(() => {
                    this.clientPop('suc', '删除成功', callBack)
                })
            } else if (this.com === 'hireBidding') {
                materialZhouCaiLeasingRequest.documenDelete(ids).then(() => {
                    this.clientPop('suc', '删除成功', callBack)
                })
            } else if (this.com === 'serviceBidding') {
                materialServiceProcurementRequest.documenDelete(ids).then(() => {
                    this.clientPop('suc', '删除成功', callBack)
                })
            } else if (this.com === 'equipmentBidding') {
                equipmentProcurementRequest.documenDelete(ids).then(() => {
                    this.clientPop('suc', '删除成功', callBack)
                })
            } else if (this.com === 'equipHireBidding') {
                equipmentLeasingRequest.documenDelete(ids).then(() => {
                    this.clientPop('suc', '删除成功', callBack)
                })
            }
        },
        downFile () {
            if (this.selection[0]?.filePath) {
                window.open(this.selection[0].filePath)
            }
            // commonRequest.downBlob(this.selection[0].filePath).then(res => {
            //     console.log(res)
            // })
        },
        selectionChange (selection) {
            this.selection = selection
        },
        // 查询公文
        documentListByEntity () {
            if (this.com === 'bidding') {
                tenderRequest
                    .documentListByEntity({
                        billId: this.tenderId,
                        limit: 20,
                        page: 1
                    })
                    .then(res => {
                        console.log('rereer', res)
                        if (res.data === null) {
                            this.tableData = []
                            return
                        }
                        res.list.forEach(item => {
                            item.changeType = 0
                        })
                        this.tableData = res.list
                        this.cloneTableData = JSON.parse(JSON.stringify(res.list)) // 用来判断是否修改过
                        // console.log(this.tableData)
                    })
            } else if (this.com === 'otherBidding') {
                engineeringOtherRequest
                    .documenListByEntity({
                        billId: this.tenderId,
                        limit: 20,
                        page: 1
                    })
                    .then(res => {
                        if (res.data === null) {
                            this.tableData = []
                            return
                        }
                        res.list.forEach(item => {
                            item.changeType = 0
                        })
                        this.tableData = res.list
                        this.cloneTableData = JSON.parse(JSON.stringify(res.list)) // 用来判断是否修改过
                        // console.log(this.tableData)
                    })
            } else if (this.com === 'materialBidding') {
                materialProvisioningRequest
                    .documenListByEntity({
                        billId: this.tenderId
                        // limit: 20,
                        // page: 1
                    })
                    .then(res => {
                        // console.log('materialBidding', res)
                        if (res.length === 0) {
                            this.tableData = []
                            return
                        }
                        res.forEach(item => {
                            item.changeType = 0
                        })
                        this.tableData = res
                        this.cloneTableData = JSON.parse(JSON.stringify(res)) // 用来判断是否修改过
                        // console.log(this.tableData)
                    })
            } else if (this.com === 'hireBidding') {
                materialZhouCaiLeasingRequest
                    .documenListByEntity({
                        billId: this.tenderId
                        // limit: 20,
                        // page: 1
                    })
                    .then(res => {
                        // console.log('materialBidding', res)
                        if (res.length === 0) {
                            this.tableData = []
                            return
                        }
                        res.forEach(item => {
                            item.changeType = 0
                        })
                        this.tableData = res
                        this.cloneTableData = JSON.parse(JSON.stringify(res)) // 用来判断是否修改过
                        // console.log(this.tableData)
                    })
            } else if (this.com === 'serviceBidding') {
                materialServiceProcurementRequest
                    .documenListByEntity({
                        billId: this.tenderId
                        // limit: 20,
                        // page: 1
                    })
                    .then(res => {
                        // console.log('materialBidding', res)
                        if (res.length === 0) {
                            this.tableData = []
                            return
                        }
                        res.forEach(item => {
                            item.changeType = 0
                        })
                        this.tableData = res
                        this.cloneTableData = JSON.parse(JSON.stringify(res)) // 用来判断是否修改过
                        // console.log(this.tableData)
                    })
            } else if (this.com === 'equipmentBidding') {
                equipmentProcurementRequest
                    .documenListByEntity({
                        billId: this.tenderId
                        // limit: 20,
                        // page: 1
                    })
                    .then(res => {
                        // console.log('materialBidding', res)
                        if (res.length === 0) {
                            this.tableData = []
                            return
                        }
                        res.forEach(item => {
                            item.changeType = 0
                        })
                        this.tableData = res
                        this.cloneTableData = JSON.parse(JSON.stringify(res)) // 用来判断是否修改过
                        // console.log(this.tableData)
                    })
            } else if (this.com === 'equipHireBidding') {
                equipmentLeasingRequest
                    .documenListByEntity({
                        billId: this.tenderId
                        // limit: 20,
                        // page: 1
                    })
                    .then(res => {
                        // console.log('materialBidding', res)
                        if (res.length === 0) {
                            this.tableData = []
                            return
                        }
                        res.forEach(item => {
                            item.changeType = 0
                        })
                        this.tableData = res
                        this.cloneTableData = JSON.parse(JSON.stringify(res)) // 用来判断是否修改过
                        // console.log(this.tableData)
                    })
            }
        }
    }
}
</script>
<style lang="scss" scoped></style>
